package demo.IOStream;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/13-08-13-13:43
 * @Description：demo.IOStream
 */
public class PipeStream {
    public static void main(String[] args) {
        PipedInputStream pis = new PipedInputStream();
        PipedOutputStream pos = new PipedOutputStream();

        try {
            pis.connect(pos);
            new WriteThread(pos).start();
            Thread.sleep(10);
            new ReadThread(pis).start();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class WriteThread extends Thread{
    private PipedOutputStream pos;

    public WriteThread(PipedOutputStream pos) {
        this.pos = pos;
    }

    @Override
    public void run() {
        byte[] b = "Hello CoreJava".getBytes();
        try {
            pos.write(b);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                pos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}class ReadThread extends Thread{
    private PipedInputStream pis;

    public ReadThread(PipedInputStream pis) {
        this.pis = pis;
    }

    @Override
    public void run() {
        try {
            byte[] b = new byte[1024];
            int len = -1;
            while((len = pis.read(b)) != -1){
                System.out.write(b,0,len);
                System.out.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                pis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
